package com.gitee.zhanyao.single.security;

import com.gitee.zhanyao.single.system.entity.SysUser;
import com.gitee.zhanyao.single.system.service.SysUserAccountService;
import com.gitee.zhanyao.single.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserAccountService sysUserAccountService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserAccountService.findByLoginName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("该用户不存在");
        }
        Set<String> authoritiySet = sysUserRoleService.getDistinctUserRoles(sysUser.getId());
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String authority : authoritiySet) {
            authorities.add(new SimpleGrantedAuthority(authority));
        }
        return new User(sysUser.getNickname(), sysUser.getPassword(), authorities);
    }

}
